package com.example.administrator.jim;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.jim.adapter.MainActivity_ViewPagerAdapter;
import com.example.administrator.jim.addresslist.AddressListView;
import com.example.administrator.jim.addresslist.SearChFriendActivity;
import com.example.administrator.jim.addresslist.UserInfoDescActivity;
import com.example.administrator.jim.bean.UserInfoBean;
import com.example.administrator.jim.bottomdialog.AddMenueBottomDialog;
import com.example.administrator.jim.imuisample.messages.MessageListActivity;
import com.example.administrator.jim.value.MyValue;
import com.example.administrator.jim.view.main.MessageView;
import com.example.administrator.jim.view.main.Mine_SettingActivity;
import com.example.administrator.jim.view.main.Mine_view;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.event.MyInfoUpdatedEvent;
import cn.jpush.im.android.api.event.NotificationClickEvent;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import it.sephiroth.android.library.bottomnavigation.BottomNavigation;

import static cn.jpush.im.android.api.JMessageClient.FLAG_NOTIFY_DEFAULT;


public class MainActivity extends BaseActivity {
    @BindView(R.id.mainactivity_BottomNavigation)
    BottomNavigation mBottomNavigation;
    @BindView(R.id.mainactivity_title)
    RelativeLayout mRelativeLayout_title;
    @BindView(R.id.mainactivity_title_textview)
    TextView mTextView_title;
    @BindView(R.id.mainactivity_viewpager)
    ViewPager mViewPager;
    @BindView(R.id.mainactivity_title_mine_setting)
    ImageView mImageView_setting;
    @BindView(R.id.mainactivity_title_mine_huitui)
    ImageView mImageView_huitui;
    @BindView(R.id.mainactivity_title_img_add)
    ImageView mMainactivityTitleImgAdd;
    @BindView(R.id.mainactivity_title_img_search)
    ImageView mMainactivityTitleImgSearch;
    private ArrayList<View> mViewDatas;
    public static UserInfo mMyInfo;
    private Mine_view mMine_view;
    private AddressListView mAddressListView;
    //更新数据标记
    public static boolean updateflag = false;
    private MessageView mMessageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setClazz(MainActivity.class);
        //加载用户信息
        mMyInfo = JMessageClient.getMyInfo();
        //隐藏系统标题栏
        getSupportActionBar().hide();
        ButterKnife.bind(this);
        //添加事件
        initListener();
        //加载viewPager
        initViewPager();

    }

    private void initListener() {
        //底部导航时间
        initBottomBarListener();
        //ViewPager事件
        initViewPagerListener();
    }

    @Override
    public void onBackPressed() {
        Intent home=new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

    private void initViewPagerListener() {
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mBottomNavigation.setSelectedIndex(position, true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initViewPager() {
        mViewDatas = new ArrayList<>();
        mAddressListView = new AddressListView(this);
        mMine_view = new Mine_view(this);
        mMessageView = new MessageView(this);
        mViewDatas.add(mMessageView);
        mViewDatas.add(mAddressListView);
        mViewDatas.add(mMine_view);
        mViewPager.setAdapter(new MainActivity_ViewPagerAdapter(mViewDatas));
    }

    private void hideorshowmine(boolean flag) {
        if (flag) {
            mImageView_setting.setVisibility(View.VISIBLE);
            mImageView_huitui.setVisibility(View.VISIBLE);
        } else {
            mImageView_setting.setVisibility(View.GONE);
            mImageView_huitui.setVisibility(View.GONE);
        }
    }

    private void initBottomBarListener() {
        mBottomNavigation.setOnMenuItemClickListener(new BottomNavigation.OnMenuItemSelectionListener() {
            @Override
            public void onMenuItemSelect(@IdRes int i, int i1, boolean b) {
                //显示顶部小红点
                //                BadgeProvider badgeProvider = mBottomNavigation.getBadgeProvider();
                //                badgeProvider.show(mBottomNavigation.getMenuItemId(i1));
                mViewPager.setCurrentItem(i1);
                switch (i1) {
                    case 0:
                        mRelativeLayout_title.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                        mTextView_title.setText("消息");
                        mMainactivityTitleImgAdd.setVisibility(View.VISIBLE);
                        mMainactivityTitleImgSearch.setVisibility(View.VISIBLE);
                        hideorshowmine(false);
                        break;
                    case 1:
                        mRelativeLayout_title.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
                        mTextView_title.setText("通讯录");
                        mMainactivityTitleImgAdd.setVisibility(View.VISIBLE);
                        mMainactivityTitleImgSearch.setVisibility(View.VISIBLE);
                        hideorshowmine(false);
                        break;
                    case 2:
                        mRelativeLayout_title.setBackgroundColor(getResources().getColor(R.color.mine));
                        mTextView_title.setText("");
                        mMainactivityTitleImgAdd.setVisibility(View.GONE);
                        mMainactivityTitleImgSearch.setVisibility(View.GONE);
                        hideorshowmine(true);
                        break;
                }
            }

            @Override
            public void onMenuItemReselect(@IdRes int i, int i1, boolean b) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //执行退出登录
        JMessageClient.logout();
    }

    @Override
    protected void onResume() {
        super.onResume();
        JMessageClient.setNotificationFlag(FLAG_NOTIFY_DEFAULT);
        if (updateflag) {
            //当再次回到此页面进行信息更新
            mMine_view.updateUserinfo();
            updateflag = false;
        }
        mMessageView.initMessageList();
        mMine_view.updateNikname();
    }
    public void onEventMainThread(MyInfoUpdatedEvent event) {
        //当数据更新时对显示的数据进行更新
        mMyInfo = event.getMyInfo();
        mMine_view.updateUserinfo();
    }

    @OnClick({R.id.mainactivity_title_mine_setting, R.id.mainactivity_title_mine_huitui,R.id.mainactivity_title_img_add,R.id.mainactivity_title_img_search})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mainactivity_title_mine_setting:
                startActivity(new Intent(MainActivity.this, Mine_SettingActivity.class));
                break;
            case R.id.mainactivity_title_mine_huitui:
                mBottomNavigation.setSelectedIndex(1, true);
                break;
            case R.id.mainactivity_title_img_add:
                AddMenueBottomDialog addMenueBottomDialog = new AddMenueBottomDialog();
                addMenueBottomDialog.show(getSupportFragmentManager());
                break;
            case R.id.mainactivity_title_img_search:
                Intent intent = new Intent(this, SearChFriendActivity.class);
                intent.putExtra(MyValue.SEARCHFRIEND_TITLE,"查找");
                startActivity(intent);
                break;
        }
    }

    public void onEventMainThread(NotificationClickEvent event) {
        Message msg = event.getMessage();
        final Intent notificationIntent = new Intent(getApplicationContext(), MessageListActivity.class);
        MessageContent content = msg.getContent();
        String userName1 = msg.getFromUser().getUserName();
        switch (msg.getContentType()) {
            case text:
                notificationIntent.setFlags(1);
                notificationIntent.putExtra("username",userName1);
                startActivity(notificationIntent);
                break;
            case image:
                notificationIntent.setFlags(1);
                notificationIntent.putExtra("username",userName1);
                startActivity(notificationIntent);
//                ImageContent imageContent = (ImageContent) content;
//                imageContent.downloadThumbnailImage(msg, new DownloadCompletionCallback() {
//                    @Override
//                    public void onComplete(int i, String s, File file) {
//                        if (i == 0) {
//                            notificationIntent.setFlags(2);
//                            notificationIntent.putExtra("image_path", file.getAbsolutePath());
//                            startActivity(notificationIntent);
//                        }
//                    }
//                });
//                final List<String> list = new ArrayList<String>();
//                msg.setOnContentDownloadProgressCallback(new ProgressUpdateCallback() {
//                    @Override
//                    public void onProgressUpdate(double v) {
//                        String progressStr = (int) (v * 100) + "%";
//                        list.add(progressStr);
//                        notificationIntent.putStringArrayListExtra(SET_DOWNLOAD_PROGRESS, (ArrayList<String>) list);
//                    }
//                });
//                boolean callbackExists = msg.isContentDownloadProgressCallbackExists();
//                notificationIntent.putExtra(IS_DOWNLOAD_PROGRESS_EXISTS, callbackExists + "");
                break;
            case voice:
                notificationIntent.setFlags(1);
                notificationIntent.putExtra("username",userName1);
                startActivity(notificationIntent);
                break;
            case file:
                break;
            case location:
                break;

            default:
                break;
        }
    }
    @Override
// 通过 onActivityResult的方法获取 扫描回来的 值
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
        if(intentResult != null) {
            if(intentResult.getContents() != null) {
                String ScanResult = intentResult.getContents();
                final UserInfoBean mUserInfoBean=new UserInfoBean();
                JMessageClient.getUserInfo(ScanResult, new GetUserInfoCallback() {
                    @Override
                    public void gotResult(int i, String s, UserInfo userInfo) {
                        if(i==0){
                            mUserInfoBean.setNikkname(userInfo.getNickname());
                            mUserInfoBean.setBeizhu(userInfo.getNotename());
                            if(userInfo.getBirthday()>0){
                                mUserInfoBean.setBirthdry(paseTime(userInfo.getBirthday()));
                            }else {
                                mUserInfoBean.setBirthdry("");
                            }
                            mUserInfoBean.setUsername(userInfo.getUserName());
                            mUserInfoBean.setGexingqianm(userInfo.getSignature());
                            if(String.valueOf(userInfo.getGender()).equals("male")) {
                                mUserInfoBean.setGender("男");
                            }else if(String.valueOf(userInfo.getGender()).equals("female")) {
                                mUserInfoBean.setGender("女");
                            }else {
                                mUserInfoBean.setGender("保密");
                            }
                            mUserInfoBean.setDiqu(userInfo.getAddress());
                            Intent intent=new Intent(MainActivity.this,UserInfoDescActivity.class);
                            intent.putExtra("isfriend",userInfo.isFriend());
                            mUserInfoBean.setBitmap(null);
                            intent.putExtra("userinfo",mUserInfoBean);
                            startActivity(intent);
                        }
                    }
                });
            }
        } else {
            super.onActivityResult(requestCode,resultCode,data);
        }
    }
    //转换时间为年月日显示
    private String paseTime(long time) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= new Date(time);
        return format.format(date);
    }
}
